package com.ruoyi.file.service;

import com.ruoyi.common.core.Entity.HttpStatusCode;
import com.ruoyi.common.core.Entity.MessageConstant;
import com.ruoyi.common.core.Entity.Result;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.file.config.MinioConfig;
import io.minio.*;
import io.minio.http.Method;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class MinIOFileServiceImpl implements MinIOFileService {

    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient minioClient;

    private static final Logger log = LoggerFactory.getLogger(MinIOFileServiceImpl.class);

    /**
     * 多文件上传方法
     *
     * @param file 文件对象数组
     * @return 文件预览路径集合
     * @Author ChengLee
     * @Date 2022/11/25
     */
    @Transactional
    @Override
    public List<String> MinIOUpload(MultipartFile[] file) {
        List<String> PreviewUrlList = new ArrayList<>();
        for (MultipartFile multipartFile : file) {
            try {
                MultipartFile uploadMultipartFile;
                String originalFileName = multipartFile.getOriginalFilename();
                if (StringUtils.isEmpty(originalFileName)) {
                    throw new RuntimeException(MessageConstant.FILE_NAME_CAN_NOT_BE_NULL);
                }
                String[] nameSplits = originalFileName.split("\\.");
                String extentName = nameSplits[nameSplits.length - 1];//获取文件扩展名
                // 如果文件类型是图片，判断是否需要压缩
                if (Arrays.asList(new String[]{"bmp", "jpg", "png", "jpeg",
                        "tif", "gif", "pcx", "tga", "exif", "fpx", "svg", "psd", "cdr", "heic",
                        "pcd", "dxf", "ufo", "eps", "ai", "raw", "WMF", "webp", "blob"}).contains(extentName)) {
                    if (multipartFile.getSize() / 1024 > 500) { //如果图片文件大小大于500KB，进行压缩
                        uploadMultipartFile = ImageCompression(multipartFile);
                    } else {
                        uploadMultipartFile = multipartFile;
                    }
                } else {
                    uploadMultipartFile = multipartFile;
                }
                String fileName = uploadMultipartFile.getOriginalFilename();
                //为保证文件名唯一性，在文件名中添加时间戳
                String prefix = fileName.substring(0, fileName.lastIndexOf("."));
                String suffix = fileName.substring(fileName.lastIndexOf("."));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                String FileName = prefix + sdf.format(new Date()) + suffix;
                log.info("实际上传文件名：" + FileName + "," + "实际上传文件大小：" + uploadMultipartFile.getSize());
                InputStream inputStream = uploadMultipartFile.getInputStream();
                //判断存储桶是否存在
                boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConfig.getBucketName())
                        .build());
                if (!bucketExists) {
                    // 如果桶不存在，按配置名称创建新桶
                    minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConfig.getBucketName()).build());
                }
                //上传文件
                minioClient.putObject(PutObjectArgs.builder().bucket(minioConfig.getBucketName()).object(FileName).stream(
                        inputStream, uploadMultipartFile.getSize(), -1).contentType(uploadMultipartFile.getContentType()).build());
                inputStream.close();
                String PreviewUrl = "http://yibinmall.chenglee.top:9000/" + minioConfig.getBucketName() + "/" + FileName;
                PreviewUrlList.add(PreviewUrl);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return PreviewUrlList;
    }

    /**
     * 图片压缩方法
     * @param file MultipartFile文件对象
     * @return 压缩后的图片对象
     * @Author ChengLee
     * @Date 2023/02/23
     */
    public MultipartFile ImageCompression(MultipartFile file) throws IOException {
        MultipartFile returnMultipartFile = null;
        String fileName = file.getOriginalFilename();
        if (!StringUtils.isBlank(fileName)) {
            long originalSize = file.getSize();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream(file.getBytes().length);
            Thumbnails.of(file.getInputStream())
                    .scale(1f) //图片大小（长宽）压缩比例 从0-1，1表示原图
                    .outputFormat("jpg")
                    .outputQuality(0.2f) //图片质量压缩比例 从0-1，越接近 1 质量越好
                    .toOutputStream(outputStream);
            InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
            returnMultipartFile = new MockMultipartFile(fileName, fileName, String.valueOf(ContentType.IMAGE_JPEG), inputStream);
            log.info("初始大小：" + originalSize + "byte" + "，" + "压缩后文件大小：" + returnMultipartFile.getSize() + "byte.");
        }
        return returnMultipartFile;
    }

    /**
     * 单文件下载方法
     *
     * @param fileName 要下载的文件名
     * @param response HttpServletResponse对象
     * @return 结果对象
     * @Author ChengLee
     * @Date 2023/01/07
     */
    @Override
    public Result MinIODownload(String fileName, HttpServletResponse response) {
        try {
            //判断存储桶是否存在
            boolean isBucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConfig.getBucketName()).build());
            //如果不存在，返回空桶提示
            if (!isBucketExists) {
                return new Result(HttpStatusCode.ERROR, MessageConstant.STORE_BUCKET_NOT_EXISTS);
            }
            //获取文件数据对象（这一步可判断文件是否存在，如果不存在，直接抛文件不存在异常并返回）
            StatObjectResponse statObjectResponse = minioClient.statObject(
                    StatObjectArgs.builder().bucket(minioConfig.getBucketName()).object(fileName).build());
            //如果大小为 0，返回空文件提示
            if (statObjectResponse.size() == 0) {
                return new Result(HttpStatusCode.ERROR, MessageConstant.FILE_SIZE_IS_ZERO);
            }
            //以流的形式获取文件对象
            InputStream stream;
            stream = minioClient.getObject(GetObjectArgs.builder().bucket(minioConfig.getBucketName())
                    .object(fileName).build());
            //下载时显示的文件名，设置字符集避免乱码
            String Filename = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Content-Disposition", "attachment;filename=" + Filename);
            ServletOutputStream servletOutputStream = response.getOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = stream.read(buffer)) > 0) {
                servletOutputStream.write(buffer, 0, len);
            }
            servletOutputStream.flush();
            stream.close();
            servletOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().equals("Object does not exist")) {
                return new Result(HttpStatusCode.ERROR, MessageConstant.FILE_NOT_EXISTS);
            }
            return new Result(HttpStatusCode.ERROR, MessageConstant.DOWNLOAD_FILE_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS, MessageConstant.DOWNLOAD_FILE_SUCCESS);
    }

    /**
     * 获取预览文件 URL
     *
     * @param FileName 预览文件名
     * @return 预览文件 URL
     * @Author ChengLee
     * @Date 2023/01/07
     */
    @Override
    public Result GetPreviewURL(String FileName) {
        String PreviewURL;
        try {
            //判断存储桶是否存在
            boolean isBucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConfig.getBucketName()).build());
            //如果不存在，返回空桶提示
            if (!isBucketExists) {
                return new Result(HttpStatusCode.ERROR, MessageConstant.STORE_BUCKET_NOT_EXISTS);
            }
            //获取文件数据对象（用来判断文件是否存在，如果不存在，直接抛文件不存在异常并返回）
            minioClient.statObject(
                    StatObjectArgs.builder().bucket(minioConfig.getBucketName()).object(FileName).build());
            //获取预览 URL
            String previewURL = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .method(Method.GET)
                    .bucket(minioConfig.getBucketName())
                    .object(FileName)
//                    .expiry(7, TimeUnit.DAYS)
                    .build());
            //如果服务器配置127.0.0.1:9000，公网路径要自己拆分后拼接
            //http://127.0.0.1:9300/lee/user.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=admin%2F20221116%2Fus-east-1%2Fs3%2Faws4_
            // request&X-Amz-Date=20221116T105545Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=64411fb077c1913d1a6951b86f
            // 0a0702a61b000ef92230f3d89061a07943f2ad
//            PreviewURL =  "https://digua.hgyun.net/digua/" + previewURL.split("/",4)[3];
            PreviewURL = "http://yibinmall.chenglee.top:9000/" + minioConfig.getBucketName() + "/" + FileName;
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().equals("Object does not exist")) {
                return new Result(HttpStatusCode.ERROR, MessageConstant.FILE_NOT_EXISTS);
            }
            return new Result(HttpStatusCode.ERROR, MessageConstant.GET_PREVIEW_URL_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS, MessageConstant.GET_PREVIEW_URL_SUCCESS, PreviewURL);
    }

    /**
     * 删除文件方法
     *
     * @param FileName 要删除的文件名
     * @return 结果对象
     * @Author ChengLee
     * @Date 2023/01/07
     */
    @Override
    public Result deleteFile(String FileName) {
        try {
            //判断存储桶是否存在
            boolean isBucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConfig.getBucketName()).build());
            //如果不存在，返回空桶提示
            if (!isBucketExists) {
                return new Result(HttpStatusCode.ERROR, MessageConstant.STORE_BUCKET_NOT_EXISTS);
            }
            //获取文件数据对象（用来判断文件是否存在，如果不存在，直接抛文件不存在异常并返回）
            minioClient.statObject(
                    StatObjectArgs.builder().bucket(minioConfig.getBucketName()).object(FileName).build());
            //删除文件
            minioClient.removeObject(
                    RemoveObjectArgs.builder().bucket(minioConfig.getBucketName()).object(FileName).build());
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().equals("Object does not exist")) {
                return new Result(HttpStatusCode.ERROR, MessageConstant.FILE_NOT_EXISTS);
            }
            return new Result(HttpStatusCode.ERROR, MessageConstant.DELETE_FILE_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS, MessageConstant.DELETE_FILE_SUCCESS);
    }

}
